import { defineStore } from 'pinia'
import router from '@/router'
import adminApi from '../api/admin'

const userStore = JSON.parse(sessionStorage.userStore || '{}')
const LOGIN_PATH = (import.meta.env.VITE_APP_BASE || '') + '/login'

export const useUserStore = defineStore({
  id: 'userStore',
  state: () => {
    return {
      username: null,
      roleId: null,
      ...userStore,
    }
  },
  getters: {
    isAdmin() {
      return this.roleId == 1
    },
  },
  actions: {
    // 登录成功
    login(data, goUrl) {
      console.log('data', data)

      return adminApi.login(data).then((res) => {
        this.username = res.username
        localStorage.token = res.token

        router.replace(goUrl || import.meta.env.VITE_APP_BASE + '/')
      })
    },

    // 重新登录(退出或token过期)
    reLogin() {
      this.clearStroe()
      this.goLogin(false)
    },

    // 清空信息
    clearStroe() {
      sessionStorage.clear()
      this.username = null
      this.roleId = null
      this.permit = null
    },

    // 去登录
    goLogin(isRedirect = true) {
      const route = router.currentRoute.value

      // 避免并发多次请求
      if (route.path == LOGIN_PATH) return

      const query = {}

      // 登录成功自动返回
      if (isRedirect) query.redirect = route.fullPath

      router.replace({
        path: LOGIN_PATH,
        query,
      })
    },

    /**
     * 登录校验
     * @returns 是否登录 true、false
     */
    checkLogin(path, goLogin = true) {
      const userStore = useUserStore()

      if (!path) {
        const route = useRoute()
        path = route.path
      }

      if (path == LOGIN_PATH) return // 不校验登录页面，避免无限重定向

      // 这里用 sessionStorage.token 判断，页面刷新会缓存 store ，故 store.token 不能用作判断
      if (!sessionStorage.token && goLogin) return userStore.reLogin()

      return true
    },
  },
})

// 页面刷新保存store
window.addEventListener('beforeunload', () => {
  const userStore = useUserStore()
  sessionStorage.userStore = JSON.stringify(userStore.$state)
})

export default useUserStore
